package br.com.suricattus.util.file;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Classe utilitaria para MIME TYPES
 * 
 * @author lucas lins
 *
 */
public abstract class MimeTypeUtil {

	private static final String MIME_TYPES = "META-INF/mime.types";
	
	private static final Map<String, String> typesMap;
	
	static{
		BufferedReader br = null;
		
		try{
			Map<String, String> map = new HashMap<String, String>();
			
			br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(MIME_TYPES)));
			String line = null;
			while((line = br.readLine()) != null){
				String[] parts = line.split("\\s+");
		        if (parts.length > 1) {
		        	String type = parts[0];
		        	if(type.startsWith("#")) continue;
		        	for(int i = 1; i < parts.length; i++) map.put(parts[i].toLowerCase(), type);
		        }
			}
			
			typesMap = Collections.unmodifiableMap(map);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(br != null){
				try{
					br.close();
				}catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
	
	/**
	 * Retorna o MimeType de acordo com a extensao do arquivo
	 * @param fileName
	 * @return
	 */
	public static String getMimeType(String fileName){
		return typesMap.get(FileUtil.getExtension(fileName));
	}
	
	/**
	 * Retorna a extensao de acordo com o MimeType.
	 * Bom, esse caso e complicado visto que para a mesma extensao podem existir diversos MimeTypes,
	 * assim retorna o primeiro que achar. Se nao achar retorna null.
	 * @param fileName
	 * @return
	 */
	public static String getExtension(String mimeType){
		mimeType = mimeType.trim();
		
		for(String key : typesMap.keySet()){
			if(mimeType.equalsIgnoreCase(typesMap.get(key))) return key;
		}
		
		return null;
	}
	
}
